#include "StatusGrpcClient.h"
#include "const.h"
#include "ConfigMgr.h"
message::GetChatServerResponse StatusGrpcClient::GetChatServer(int uid)
{
   std::unique_ptr<message::StatusServer::Stub> stub = pool_->GetConnection();
    //利用RAII机制，在函数结束时归还连接
    Defer defer([this,&stub](){
        pool_->ReturnConnection(std::move(stub));
    });



   grpc::ClientContext context;
   message::GetChatServerRequest req;
   message::GetChatServerResponse resp;
   req.set_uid(uid);
   if(!stub)
   {
       std::cerr<<"StatusGrpcClient::GetChatServer get connection failed"<<std::endl;
       resp.set_error(ErrorCodes::RPCFailed);
       return resp;
   }
   req.set_uid(uid);
   ::grpc::Status status = stub->GetChatServer(&context,req,&resp);
   if(!status.ok())
   {
       std::cerr<<"StatusGrpcClient::GetChatServer rpc failed"<<std::endl;
       resp.set_error(ErrorCodes::RPCFailed);
       return resp;
   }
   return resp;
}

StatusGrpcClient::StatusGrpcClient()
{
    ConfigMgr& cfg = ConfigMgr::GetInstance();
    std::string host = cfg["StatusServer"]["Host"];
    std::string port = cfg["StatusServer"]["Port"];
    pool_ = std::make_unique<StatusConnectionPool>(5,host,port);
}